<template>
	<div>
		<grid class="rawGridTitle" :show-vertical-dividers="false">
			<grid-item class="rawCollection">
				<span class="grid-center">删除</span>
			</grid-item>
			<grid-item @click.native="orderByFunc('name')">
				<span class="grid-center" style="margin-left: 10px;">姓名<img slot="icon" style="width: 13px" src="@/assets/svg/icon_order.svg"></span>
			</grid-item>
			<grid-item @click.native="orderByFunc('age')">
				<span class="grid-center" style="margin-left: 10px;">年龄<img slot="icon" style="width: 13px" src="@/assets/svg/icon_order.svg"></span>
			</grid-item>
			<grid-item class="rawStatus" @click.native="orderByFunc('time')">
				<span class="grid-center-status">状态<img slot="icon" style="width: 13px" src="@/assets/svg/icon_order.svg"></span>
			</grid-item>
			<grid-item>
				<span class="grid-center">电话</span>
			</grid-item>
		</grid>

		<scroller :on-refresh="refresh" :on-infinite="infinite" :noDataText="noDataText" ref="rawStudentList">
			<group id="commonScroller" class="commonScrollerMyCustomer">
				<grid class="rawGrid" v-for="(item,index) in items" :show-vertical-dividers="false">
					<grid-item class="grid-item" @click.native="onClickObsolete(item,index)">
						<span class="grid-center"><img slot="icon" style="width: 18px;" src="@/assets/svg/icon_collection.svg"></span>
					</grid-item>
					<grid-item class="grid-item" @click.native="jumpTo(item.id)">
						<span class="grid-center-name">{{item.name.substring(0,3)}}</span>
					</grid-item>
					<grid-item class="grid-item">
						<span v-if="item.age == null" class="grid-center">无</span>
						<span v-else class="grid-center">{{item.age}}</span>
					</grid-item>
					<grid-item class="rawStatus">
						<span v-if="item.time == null" class="grid-center-status">无</span>
						<span v-else-if="item.comments == null" class="grid-center-status">{{formatTime(item.time) + '，无备注'}}</span>
						<span v-else class="grid-center-status">{{formatTime(item.time) + '，' + item.comments.substring(0,5)}}</span>
					</grid-item>
					<grid-item class="grid-item" @click.native="callCustomer(item,index)">
						<span class="grid-center"><img slot="icon" style="width: 18px;" src="@/assets/svg/icon_phone.svg"></span>
					</grid-item>
				</grid>
			</group>
		</scroller>

		<div v-transfer-dom>
			<x-dialog v-model="obsoleteShow" class="popDialog">
				<p class="reason">请选择丢弃 <span style="color: #ff9d9d">'{{curItem.name}}'</span> 的原因<x-icon type="ios-close-outline" style="fill:white;float: right;" @click="obsoleteShow = false"></x-icon></p>
				<div class="img-box" style="height:350px;padding:15px 10px;overflow:scroll;-webkit-overflow-scrolling:touch;">
					<checklist class="checkList" :options="obsoleteReasons" v-model="reason" :max="1" @on-change="onChange"></checklist>
					<div class="error" v-show="error">{{error}}</div>
					<flexbox>
						<flexbox-item>
							<x-button class="flexBtn_confirm" :gradients="['#FF5E3A', '#FF9500']" @click.native="obsoleteCustomer">确定</x-button>
						</flexbox-item>
					</flexbox>
				</div>
			</x-dialog>
		</div>

		<div v-transfer-dom>
			<popup v-model="showIfConnected" :hide-on-blur=false height="270px" is-transparent>
				<div style="width: 95%;background-color:#fff;margin:0 auto;padding-bottom: 5px">
					<group>
						<checker v-model="action" style="margin-top: 20px" default-item-class="checkDefault" selected-item-class="checkDefaultSelected">
							<span style="margin-left: 5px;font-size: 13px;background-color: rgb(200, 2, 23);padding: 5px 5px; margin-right: 10px; color: white">下步操作</span>
							<checker-item :value="item" v-for="(item, index) in actionItems" :key="index">{{item.name}}</checker-item>
						</checker>
						<x-textarea :max="200" :placeholder="hint"  v-model="detail" :height="50" ></x-textarea>
					</group>
					<flexbox>
						<flexbox-item>
							<x-button class="flexBtn_confirm" @click.native="confirm">提交</x-button>
						</flexbox-item>
						<flexbox-item>
							<x-button class="flexBtn_cancel" @click.native="cancel">取消</x-button>
						</flexbox-item>
					</flexbox>
				</div>
			</popup>
		</div>
	</div>
</template>

<script>
	import Vue from 'vue'
	import DateUtil from '../../../utils/date'
	import NetWorking from '../../../utils/networking'
	import { XDialog, Checklist, Loading, Group, Cell, ConfirmPlugin, Tab, TabItem, FormPreview, Grid, GridItem, TransferDom, Popup, Flexbox, FlexboxItem, XButton, XTextarea, Checker, CheckerItem} from 'vux'
	import VueScroller from 'vue-scroller'
	Vue.use(VueScroller)
	Vue.use(ConfirmPlugin)

	const SIZE = 20

	export default {
		name: "scrollerMyRawCustomer",
		components: {
			XDialog,
			Checklist,
			Loading,
			Group,
			Cell,
			Tab,
			TabItem,
			FormPreview,
			Grid,
			GridItem,
			TransferDom,
			Popup,
			Flexbox,
			FlexboxItem,
			XButton,
			XTextarea,
			Checker,
			CheckerItem
		},
		directives: {
			TransferDom
		},
		props: ['curURL', 'jumpToObjectDetails', 'orderBy','sequence','username','status'],
		data() {
			return {
				fileId: '',
				now: Date.parse(new Date()) / 1000,
				expire: 0,
				policy: '',
				obsoleteShow: false,
				obsoleteItems: [],
				obsoleteReasons: [],
				reason: [],
				showSpin: false,
				isApp: true,
				id: '',
				detail: '',
				hint: '通话详细内容',
				showPopup: false,
				showIfConnected: false,
				action: {name: '再沟通', value: 8},
				actionItems: [{name: '再沟通', value: 8}, {name: '转为准客户', value: 0}, {name: '丢弃', value: '2'}],
				noDataText: '',
				offset: 0,
				limit: SIZE,
				noMoreData: false,
				items: [],
				list: [],
				curItem: '',
				curIndex: 0,
				mediaRec: '',
				recordFile: '',
				error: ''
			}
		},
		beforeCreate: function () {
			let _this = this
			document.addEventListener("deviceready", onDeviceReady, false);
			function onDeviceReady() {
				CallTrap.onCall(({state, number, duration}) => {
					console.log(`CHANGE STATE: ${state}`)
					switch (state) {
						case CallTrap.STATE.RINGING:
							console.log('Phone is ringing', number)
							break
						case CallTrap.STATE.OFFHOOK:
							//响铃后开始录音，因为系统权限的问题，目前我们能拿到的就是当前这3种状态
							_this.recordMedia()
							console.log('Phone is off-hook')
							break
						case CallTrap.STATE.IDLE:
							//挂机后停止录音
							_this.stopRecordMedia()
							_this.hideLoading()
							console.log('通话时间：' + duration + '秒')
							if(duration > 0){
								_this.upload()
							}else{
								_this.unconnected()
							}
							break
					}
				})
			}
		},
		created: function () {
			if(!navigator.userAgent.match('DuoZhaoApp')){
				this.isApp = false
			}

			let _this = this
			NetWorking.doGet(
				'list_of_value/getListOfValueByType',
				null,
				{
					params: {
						type: 'S_LOV_OBSOLETE_REASON'
					}
				}
			).then(
				response => {
					let rs = response.data
					if(rs.error_code == 0){
						_this.obsoleteItems = rs.list_of_value
						for(let i=0; i<_this.obsoleteItems.length; i++){
							_this.obsoleteReasons.push(_this.obsoleteItems[i].value)
						}
					}else{
						alert(rs.error_message)
					}
				}
			)
		},
		watch: {
			curURL: function () {
				this.resetData()
			},
			orderBy: function () {
				this.resetData()
			},
			sequence: function () {
				this.resetData()
			},
			status: function () {
				this.resetData()
			}
		},
		methods:{
			onChange (val) {
				console.log(val)
			},
			onClickObsolete (item, index) {
				this.curItem = item
				this.curIndex = index
				this.obsoleteShow = true
			},
			obsoleteCustomer: function () {
				if(this.reason.length == 0){
					this.error = "请选择丢弃原因"
					return
				}

				let _this = this
				NetWorking.doPost(
					'customers/obsoleteCustomer',
					null,
					null,
					{
						params: {
							id: this.curItem.id,
							obsolete_tag: this.reason[0]
						}
					}
				).then(
					response => {
						let rs = response.data
						if(rs.error_code == 0){
							_this.items.splice(this.curIndex, 1)
							this.obsoleteShow = false
						}else{
							alert(rs.error_message);
						}
						this.reason = ''
					}
				)
			},
			showLoading () {
				this.$vux.loading.show({
					text: '请稍等...'
				})
			},
			hideLoading () {
				this.$vux.loading.hide()
			},
			triggerrefresh()
			{
				this.noDataText = ''
				this.offset = 0
				this.limit = SIZE
				this.noMoreData = false
				this.items = []
				this.$refs.rawStudentList.finishPullToRefresh(false)
				this.$refs.rawStudentList.finishInfinite(false)
				this.infinite(done)
			},
			recordMedia: function () {
				//var src = "cdvfile://localhost/temporary/recording.mp3";
				let randomNumber = DateUtil.getYYMMDD(new Date()) + Math.floor(Math.random()*899999+100000);
				this.recordFile = "myRecordMedia" + randomNumber + ".mp3"
				let src = this.recordFile
				this.mediaRec = new Media(src, this.onSuccess, this.onError)
				if(this.mediaRec){
					this.mediaRec.startRecord()
				}else{
					alert('系统错误，请重试')
				}
			},
			stopRecordMedia: function () {
				if(this.mediaRec){
					this.mediaRec.stopRecord()
					this.mediaRec.release()
				}
			},
			onSuccess: function () {
				console.log("recordAudio():Audio Success");
			},
			onError: function () {
				console.log("recordAudio():Audio Failed");
			},
			callCustomer: function (item,index) {
				if(!this.isApp){
					alert('该功能需要在APP中使用')
					return
				}else{
					let _this = this
					window.plugins.CallNumber.callNumber(function onSuccess(result){
							setTimeout(function(){
								//_this.showPopup = true
								_this.id = item.id
								_this.curItem = item
								_this.curIndex = index
								_this.showLoading()

							}, 1000)
						},
						function onError(result) {
							alert("通话失败，请重试")
						},
						item.phone,true)
				}
			},
			upload() {
				let _this = this
				window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, function (dirEntry) {
					dirEntry.getFile(_this.recordFile,{},function (fileEntry) {
						fileEntry.file(function (file) {
							var win = function (r) {
								let obj = JSON.parse(r.response)
								_this.fileId = obj.fileId
								_this.showIfConnected = true
							}

							var fail = function (error) {
								this.detail = '声音文件上传失败(error.code = ' + error.code + '),' + this.detail
								_this.fileId = ''
								_this.showIfConnected = true

								//alert("An error has occurred: Code = " + error.code);
								console.log("upload error source " + error.source);
								console.log("upload error target " + error.target);
							}

							_this.getSignature()
							var options = new FileUploadOptions();
							options.fileKey = "file";
							options.fileName = file.localURL.substr(file.localURL.lastIndexOf('/') + 1);
							options.mimeType = "audio/mpeg";
							options.headers = {
								Connection: "close"
							};

							const suffix = _this.getSuffix(options.fileName);
							let g_object_name = _this.policy.dir + _this.randomString(10) + suffix;

							const newMultipartParams = {
								key: g_object_name,
								policy: _this.policy.policy,
								OSSAccessKeyId: _this.policy.accessid,
								// 让服务端返回200,不然，默认会返回204
								success_action_status: '200',
								signature: _this.policy.signature,
								callback: _this.policy.callback,
							};

							options.params = newMultipartParams;

							var ft = new FileTransfer();
							ft.upload(file.localURL, encodeURI(_this.policy.host), win, fail, options);
						},_this.errorHandler)
					},_this.errorHandler)
				},_this.errorHandler)
			},
			randomString(len = 32) {
				const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
				const maxPos = chars.length;
				let pwd = '';
				for (let i = 0; i < len; i += 1) {
					pwd += chars.charAt(Math.floor(Math.random() * maxPos));
				}
				return pwd;
			},
			getSuffix(filename) {
				const pos = filename.lastIndexOf('.');
				let suffix = '';
				if (pos !== -1) {
					suffix = filename.substring(pos);
				}
				return suffix;
			},
			sendRequest() {
				const xmlhttp = new XMLHttpRequest();
				// 你的服务端接口地址:  参考demo:http://oss-demo.aliyuncs.com/oss-h5-upload-js-php/
				// 服务端签名后直传文档:  https://help.aliyun.com/document_detail/31926.html
				const serverUrl = 'http://www.edumavin.com:8080/api/oss/postpolicy';
				xmlhttp.open('GET', serverUrl, false);
				xmlhttp.setRequestHeader('Authorization', this.$store.state.user.token)
				xmlhttp.send(null);
				return xmlhttp.responseText;
			},
			getSignature() {
				// 可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
				this.now = Date.parse(new Date()) / 1000;
				if (this.expire < this.now + 3) {
					const body = this.sendRequest();
					const e = eval;
					const obj = e(`(${body})`);
					this.policy = obj.postpolicy;
					return true;
				}
				return false;
			},
			errorHandler: function () {
				console.log("Error happened")
			},
			unconnected: function () {
				let _this = this
				NetWorking.doPost(
					'customertrace',
					null,
					null,
					{
						params: {
							content: '未接通' ,
							customerId: this.id,
							file_id: ''
						}
					}
				).then(
					response => {
						let rs = response.data
						if(rs.error_code == 0){
							_this.detail = ''
							_this.showPopup = false
							_this.updateItem(rs.trace)
						}else{
							alert(rs.error_message)
						}
					}
				)
			},
			updateItem: function (trace) {
				this.items[this.curIndex].time = trace.create_time
				this.items[this.curIndex].comments = trace.content
			},
			jumpTo: function (id) {
				//组件间传递参数
				this.$router.push({ name: "customerDetails", params: { id: id, index: 1}})
			},
			formatTime: function (time) {
				return DateUtil.getTimeWhile(time)
			},
			confirm: function () {
				this.showIfConnected = false
				let curTime = DateUtil.getYYMMDDHHmm(new Date())
				var url_trace = 'customertrace'
				var url_act = 'activities/attachCallActivity'
				var url_cus = 'customers/updateCustomerField'
				var urlarr = new Array()
				urlarr.push(
					NetWorking.doPost(
						url_trace,
						null,
						null,
						{
							params: {
								content: this.action.name + '，' + this.detail,
								customerId: this.id,
								file_id: this.fileId
							}
						}
					))

				urlarr.push(
					NetWorking.doPost(
						url_act,
						null,
						{
							title: '电话',
							content: this.detail,
							time: curTime,
							status: 2 //mark call status as 2 if we confirm we've called the customer
						},
						{
							params: {
								employee_id: this.$store.state.user.userModel.sysUser.id,
								customer_id: this.id,
								rolePlay: 'consultant'
							}
						}
					))

				urlarr.push(
					NetWorking.doPost(
						url_cus,
						null,
						null,
						{
							params: {
								id: this.id,
								fieldName: "status",
								fieldValue: this.action.value
							}
						}
					))

				let _this = this
				var callback = function (c1, c2, c3) {
					let rs1 = c1.data
					let rs2 = c2.data
					let rs3 = c3.data

					if(rs1.error_code != 0 || rs2.error_code != 0 || rs3.error_code != 0){
						alert('更新记录失败，请重试')
					}else{
						_this.detail = ''
						_this.show   = false
						if(_this.action.value == 8){
							_this.items[_this.curIndex].time = rs1.trace.create_time
							_this.items[_this.curIndex].comments = rs1.trace.content
						}else{
							_this.triggerrefresh()
						}
					}
				}

				NetWorking.doAll2(urlarr).then(this.axios.spread(callback))
					.catch(function (e){
						console.log(2);
					});
			},
			cancel: function () {
				this.showIfConnected = false
			},
			orderByFunc: function (value) {
				this.orderBy = value
				if(this.sequence == 'asc'){
					this.sequence = 'desc'
				}else{
					this.sequence = 'asc'
				}
				sessionStorage.orderBy = this.orderBy
				sessionStorage.sequence = this.sequence
			},
			resetData() {
				this.noDataText = ''
				this.offset = 0
				this.limit = SIZE
				this.noMoreData = false
				this.items = []
				this.$refs.rawStudentList.finishPullToRefresh(false)
				this.$refs.rawStudentList.finishInfinite(false)
			},
			refresh (done) {
				this.$refs.rawStudentList.finishPullToRefresh(true)
				return
			},
			infinite (done) {
				if(this.noMoreData){
					this.noDataText = '没有更多记录了——总' + this.items.length + '条'
					this.$refs.rawStudentList.finishInfinite(true)
					return
				}else{
					let _this = this
					_this.offset += 1
					this.isRunning = true
					NetWorking.doGet(
						this.curURL,
						null ,
						{
							params:{
								offset: _this.offset,
								limit: _this.limit,
								orderBy: _this.orderBy,
								sequence: _this.sequence,
								username: _this.username,
								status: _this.status
							}
						}
					).then(
						response => {
							let res = response.data
							if (res.error_code == 0) {
								if(res.page_info.list.length >= 0){
									_this.items.push.apply(_this.items, res.page_info.list)
									_this.bottom += res.page_info.list.length
									//set noMoreData flag to true if current size < limit
									if(res.page_info.list.length < _this.limit){
										_this.noMoreData = true
										_this.$refs.rawStudentList.finishInfinite(true);
									}
								}
							} else {
								alert(res.error_message)
							}
							done()
						}
					)
				}
			}
		}
	}
</script>

<style>
	.error {
		color: #ff9d9d;
	}

	.checkList > .weui-cells{
		background: transparent;
	}

	.checkList > .weui-cells:before{
		border-top: 0px solid #D9D9D9;
	}

	.checkList > .weui-cells:after{
		border-bottom: 0px solid #D9D9D9;
	}

	.checkList > .weui-cells > .weui-cell:before{
		border-top: 0px solid #D9D9D9;
	}

	.popDialogTitle {
		padding:0px 20px;
		font-weight: bold;
		font-size: 20px;
	}

	.img-box {
		height: 350px;
		overflow: hidden;
	}
	.vux-close {
		margin-top: 8px;
		margin-bottom: 8px;
	}

	.popDialog > .weui-dialog {
		text-align: left;
		width: 80%;
		height: 80%;
		max-width: initial;
		background: transparent;
		color: white;
	}

	.popDialog > .weui-mask {
		background: rgba(0, 0, 0, 0.8);
	}

	.popGroup {

	}

	.popGroup > .weui-cells {
		background: transparent;
		color: white;
	}

	.popGroup > .weui-cells:before{
		border-top: 0px solid #D9D9D9 !important;
	}

	.popGroup > .weui-cells:after{
		border-bottom: 0px solid #D9D9D9 !important;
	}

	.commonScrollerMyCustomer{
		margin-top: 122px;
	}

	.rawGridTitle{
		font-size: 12px;
		background: lightgoldenrodyellow;
		z-index: 10;
	}

	.rawGridTitle > .weui-grid {
		width: 15% !important;
	}

	.rawGridTitle > .rawStatus {
		width: 40% !important;
	}

	.rawGrid {
		font-size: 12px;
	}

	.rawGrid > .weui-grid {
		text-decoration: none;
	}

	.rawGrid > .weui-grid {
		width: 15% !important;
	}

	.rawGrid > .rawStatus {
		width: 40% !important;
	}

	.rawGrid > .rawStatus:after{
		border-bottom: 0px solid #D9D9D9 !important;
	}

	.grid-center {
		display: block;
		text-align: center;
		color: #666;
	}

	.grid-center-status {
		display: block;
		text-align: center;
		color: #b29a19;
	}

	.grid-center-name{
		display: block;
		text-align: center;
		color: #43abe3;
	}

	.poStudentList {
		margin-top: 76px;
	}

	.poStudentList > .weui-cells:before {
		border-top: none;
	}

	.tag {
		text-align: right;
		background: red;
		width: fit-content;
		color: white;
		padding-left: 5px;
		border-radius: 5px;
		padding-right: 5px;
		font-size: 13px;
	}

	.itemTime {
		display: block;
		-webkit-margin-before: 1em;
		-webkit-margin-after: 1em;
		-webkit-margin-start: 0px;
		-webkit-margin-end: 0px;
		line-height: 1.41176471;
		font-size: 13px;
	}

	.checkDefault {
		border: 1px solid #ececec;
		padding: 5px 5px;
		background-color: white;
		margin-right: 10px;
		font-size: 13px;
		margin-bottom: 10px;
	}
	
	.checkDefaultSelected {
		background: #ffffff url(../../../assets/img/icon_check.png) no-repeat right bottom;
		border-color: #ff4a00;
	}
</style>